$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'order/paperOrder/paperOrderList',
        datatype: "json",
        postData:{promotionType:'paper'},//请求参数
        colModel: [
            { label: '操作', name: 'operation',  width: '60', align: 'center', title:false,
                formatter:function(value, options, row){
                    var html = '<li class="dropdown" style="list-style: none;position: absolute;width: 60px;right: auto;left: auto;"><a href="#" style="margin:0 auto;text-decoration:none;" class="dropdown-toggle" data-toggle="dropdown">操作</a>';
                    html += '<ul class="dropdown-menu"  style="min-width:100%;font-size: 12px;">';
                    var options = [];
                    // 支付后限制编辑、审核操作
                    if (row.payStatus != '1'){
                        options.push('<li><a href="javascript:;" onclick="return edit(\''+ row.orderId +'\');">编辑</a></li><li class="divider"></li>');
                        options.push('<li><a href="javascript:;" onclick="return audit(\''+ row.orderId +'\');">审核</a></li><li class="divider"></li>');
                    }
                    options.push('<li><a href="javascript:;" onclick="return vm.orderRemark(\''+ row.orderId +'\');">备注</a></li><li class="divider"></li>');
                    options.push('<li><a href="javascript:;" onclick="return send(\''+ row.orderId +'\');">发货</a></li><li class="divider"></li>');
                    options.push('<li><a href="javascript:;" onclick="return vm.orderTax(\''+ row.orderId +'\', \''+ row.sendTax +'\');">是否开发票</a></li>');
                    html += options.join("")
                    html += '</ul></li>';
                    return html;
                }},
			{ label: '订单号', name: 'orderId', index: 'order_id', width: 80, key: true, align: 'center',hidden: true},
            { label: '订单号', name: '', index: '', width: 120, align: 'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;" onclick="return info(\''+ row.orderId +'\');">'+ row.orderId +'</a></li>';
                }
            },
            { label: '会员用户名', name: 'memberName', index: '', width: 140, align: 'center'},
            { label: '订单总额', name: 'totalAmount', index: 'total_amount', width: 80, align: 'center' },
            { label: '应付总额', name: 'payableAmount', index: 'payable_amount', width: 80, align: 'center' },
            { label: '调价', name: 'discount', index: 'discount', width: 80, align: 'center' },
            { label: '已支付额', name: 'payed', index: 'payed', width: 80, align: 'center' },
            { label: '支付信息', name: 'payInfo', index: '', width: 150, align: 'center' },
            { label: '下单时间', name: 'createtime', index: 'createtime', width: 120, align: 'center' },
            { label: '支付状态', name: 'payStatus', index: 'pay_status', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    return value == '1' ? '已支付' : '未支付';
                }},
            { label: '审核状态', name: 'productionStatusText', index: '', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    if (value != '待审核'){
                        return '已审核';
                    }
                    return value;
                }},
            { label: '审核人', name: 'auditName', index: '', width: 80, align: 'center' },
            { label: '审核时间', name: 'auditTime', index: '', width: 120, align: 'center' },
            { label: '收货人', name: 'shipName', index: 'ship_name', width: 80, align: 'center' },
            { label: '收货地址', name: 'shipAddr', index: 'ship_addr', width: 150, align: 'center' },
        ],
		viewrecords: true,
        height: window.innerHeight - 120,
        rowNum: 25,
		rowList : [25,50,75],
        rownumbers: true, 
        rownumWidth: 40,
        autowidth:true,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            //枚举参数
            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.e.orderInfoStatusEnum = userData.orderInfoStatusEnum;
            vm.e.payTypeEnum = userData.payTypeEnum;
        }
    });
});

// 大纸订单详细信息
function info(orderId){
    vm.status = 1;
    vm.edit(orderId);
}

// 大纸订单信息编辑
function edit(orderId){
    vm.status = 2;
    vm.edit(orderId);
}

// 大纸订单信息审核
function audit(orderId){
    vm.status = 3;
    vm.edit(orderId);
}

// 大纸订单发货
function send(orderId) {
    vm.send(orderId);
}

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
        showLogi: false,
        showOrder: false,
        /* 实体 */
        paperOrderInfo:{},
        erpOrder:{},
        erpLogisticsEntity: {},      // 发货信息
        orderItemList: [],            // 订单明细
        logisticsItemList: [],      //勾选的订单明细
        showSendDetail: true,       // 是否显示发货明细
        showLogiNo: true,           // 是否显示配送单号
        logisticsTypeList: [],
        orderItemList:[],
        receiptsAccounts: [],
        userPaymentList: [],
        userPayment: {},
        /* 跳转判断 详情1 编辑2 审核3*/
        status: 0,
        /* 订单备注 */
        orderRemarks: [],
        /* 订单日志 */
        erpOrderLogs: [],
        orderLogs: [],
        /* 查询 */
        q:{
            orderId: '',
            status: '',
            orderType: '',
            beginCreatetime:'',
            endCreatetime:'',
            auditStatus:'',
            payStatus:'',
        },
        /* 枚举 */
        e:{
            payTypeEnum: [],
            goodsTypeEnum:[],
            orderInfoStatusEnum:[],
            thirdMerchantTypeEnum:[],
            taxTypeEnum:[],
            taxContentEnum: [
                {text: '订单明细'},
                {text: '印刷品'},
                {text: '纸制品'},
                {text: '设计费'},
                {text: '铜版纸'},
                {text: '双胶纸'},
                {text: '白卡纸'},
                {text: '复印纸'},
                {text: '淋膜纸'}
            ],
        },
        /* 物流发送 */
        area: {},
        /* 公用 */
        pub:{
            orderId: '',
            remark: '',
        },
        /* 送货单是否开发票 */
        taxForm: {
            orderId: '',
            sendTax: 0
        },
        /* 省市区data */
        options: [],
        /* 省市区回显 */
        areaCascader: [],
        /* 商品表单修改 */
        update:{
            paperOrderInfo: {},
            orderItem: {},
            orderItemList:[]
        },
        /* 审核金额修改 */
        audit:{
            costFreight:{},
            discount:{},
            payableAmount:{}
        },
        /* 订单支付字段 */
        username: '',
        pay:{
            bank: '',
            account: '',
            money: '',
            payName: '',
            memo: '',
            tPayed: '',
            payAppId: ''
        },
        /* 收货人信息 */
        shipForm:{
            shipTime: '',
            shipName: '',
            shipMobile: '',
            shipAddr: '',
            shipZip: '',
            sendType: '',
            costFreight: '',
            areaCascader: '',
            shipAreaId: '',
            shipArea: ''
        },
        shipFormVisible: false,
        formLabelWidth: '120px',
        /* 订单调价 */
        costForm: {
            discount: '',
            remark: ''
        },
        costFormVisible: false,
        /*  修改发票信息 */
        invoiceFrom:{
            taxType:'',
            taxIdentification:'',
            taxContent:'',
            taxAddr:'',
            taxCompany:'',
            taxTel:'',
            taxAccountName:'',
            taxNumber:'',
        },
        invoiceFormVisible:false,
        // 修改发票信息 重置按钮
        resetForm(invoiceFrom) { this.$refs[invoiceFrom].resetFields();}
	},
	methods: {
		query: function () {
			vm.reload();
		},
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
                }})
        },
        checkEndDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }})
        },
        checkSendDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false, onpicking:function (dp) {
                    if (vm.erpOrder == null){
                        vm.paperOrderInfo.shipTime = dp.cal.getNewDateStr();
                    }else {
                        vm.erpOrder.shipTime = dp.cal.getNewDateStr();
                    }
                }})
        },
        checkPayDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',isShowClear:false, onpicking:function (dp) {
                    vm.pay.tPayed = dp.cal.getNewDateStr();
                }})
        },
        /* 获取当前日期 */
        dateFormat:function(date) {
            var year=date.getFullYear();
            var month= date.getMonth()+1<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1;
            var day=date.getDate()<10 ? "0"+date.getDate() : date.getDate();
            var hours=date.getHours()<10 ? "0"+date.getHours() : date.getHours();
            var minutes=date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes();
            var seconds=date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds();
            return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
        },
        /* 银行账户 */
        receiptsAccountsChange: function (event) {
            var idx = event.target.value;
            vm.pay.bank = vm.receiptsAccounts[idx].fraBank;
            vm.pay.account = vm.receiptsAccounts[idx].fraAccount.split('-')[0];
        },
        /* 支付方式 */
        payTypeChange: function () {
            var payAppId = vm.pay.payAppId;
            var data = vm.e.payTypeEnum.find((item) => {
                return item.value == payAppId;
            });
            console.info(data);
            vm.pay.payName = data.describe;
        },
        edit: function(orderId){
            vm.showList = false;
            vm.getInfo(orderId);
        },
        /* 订单备注 */
        orderRemark: function (orderId) {
            vm.pub.orderId = orderId;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单备注",
                area: ['550px', '280px'],
                shadeClose: false,
                content: jQuery("#remarksLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderRemarks",
                        contentType: "application/json",
                        data: {
                            'orderId': vm.pub.orderId,
                            'remarks': vm.pub.remark
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                vm.pub.remark = '';
                                vm.pub.orderId = '';
                                vm.reload();
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vm.pub.remark = '';
                    vm.pub.orderId = '';
                }
            });
        },
        /* 是否开发票 */
        orderTax: function (orderId, sendTax) {
            vm.taxForm.orderId = orderId;
            vm.taxForm.sendTax = sendTax;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "送货单是否开发票",
                area: ['550px', '250px'],
                shadeClose: false,
                content: jQuery("#taxLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderTax",
                        contentType: "application/json",
                        data: {
                            'orderId': vm.taxForm.orderId,
                            'sendTax': vm.taxForm.sendTax
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                vm.taxForm.orderId = '';
                                vm.taxForm.sendTax = 0;
                                vm.reload();
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vm.taxForm.orderId = '';
                    vm.taxForm.sendTax = 0;
                }
            });
        },
        // 详情数据
        getInfo: function(orderId){
            $.get(baseURL + "order/paperOrder/info/"+orderId, function(r){
                vm.paperOrderInfo = r.paperOrderInfo;
                vm.erpOrder = r.erpOrder;
                vm.receiptsAccounts = r.receiptsAccounts;
                vm.orderItemList = r.orderItemList;
                vm.userPaymentList = r.userPaymentList;
                vm.username = r.username;

                // 扩展商品属性
                for (var o in vm.orderItemList){
                    var item = vm.orderItemList[o];
                    vm.regularAddon(item);
                }
                // 枚举类型
                vm.e.taxTypeEnum = r.taxTypeEnum;
                vm.e.thirdMerchantTypeEnum = r.thirdMerchantTypeEnum;
                vm.e.goodsTypeEnum = r.goodsTypeEnum;

                $.get(baseURL + "order/orderinfo/getOrderLogfo/" + orderId, function(r1){
                    vm.orderRemarks = r1.orderRemarks;
                    vm.erpOrderLogs = r1.erpOrderLogs;
                    vm.orderLogs = r1.orderLogs;
                });
                // 编辑回显级联省市区
                if (vm.status == 2){
                    $.get(baseURL + "freightages/sdbectoolsregions/queryRegionsSascade", function(r2){
                        vm.options = JSON.parse(r2.list);
                    });
                }

                vm.showList = false;
                vm.showLogi = false;
                vm.showOrder = true;
            });
        },
        /* 显示调价表单 */
        costFormShow: function () {
            vm.costForm.discount = vm.paperOrderInfo.discount;
            vm.costFormVisible = true;
        },
        // 修改费用信息
        changeCost: function () {
            var discount = vm.costForm.discount;
            if (discount == ''){
                alert("调价不能为空");
                return false;
            }
            if (Number(discount) == 0){
                alert("调价不能为 0 ");
                return false;
            }
            var remark = vm.costForm.remark;
            if (isBlank(remark)){
                alert("改价原因不能为空");
                return false;
            }

            $.ajax({
                type: "GET",
                url: baseURL + "order/orderinfo/orderDiscountAudit",
                contentType: "application/json",
                data: {
                    'orderId': vm.paperOrderInfo.orderId,
                    'discount': discount,
                    'remark': remark
                },
                success: function(r){
                    vm.costFormVisible = false;
                    if(r.code === 0){
                        vm.costForm.discount = '';
                        vm.costForm.remark = '';
                        vm.getInfo(vm.paperOrderInfo.orderId);
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        /* 解析商品规格 */
        regularAddon: function (item) {
            // 价格
            var price = item.price;
            // 规格属性(商品 长、宽、克重、包数、尺寸信息)
            var addon = item.addon;
            // 长、宽
            var paperSize = item.paperSize;
            // 克重
            var g = addon.match(/[0-9]*?(?=g)/)[0];
            if (item.goodsType == 'paper'){ //大纸
                if (item.paperUnit == 'ton'){ //吨价
                    Vue.set(item, 'paperWidth', paperSize); //宽
                    Vue.set(item, 'paperWeight', g); //克重
                    // 吨价
                    Vue.set(item, 'tonPrice', price);
                }else if (item.paperUnit == 'ream'){ // 令价
                    // 长、宽、克重
                    var paperSizeArr = paperSize.split(',');
                    Vue.set(item, 'paperLen', paperSizeArr[0]); //长
                    Vue.set(item, 'paperWidth', paperSizeArr[1]);//宽
                    Vue.set(item, 'paperWeight', g); //克重
                    // 令价
                    Vue.set(item, 'reamPrice', price);
                    // 吨价
                    var tonPrice = vm.calculateTonPrice(item);
                    Vue.set(item, 'tonPrice', tonPrice);
                }
            }else if (item.goodsType == 'copy'){ // 复印纸
                // 包数、尺寸
                var p = addon.match(/[0-9]+[包]/)[0].match(/\d/)[0];
                var ad = addon.match(/([AB][345])|(\d*?(?=K)+K)/)[0];
                var size = 0;
                if(ad == 'A3'){
                    size = 420 * 297
                }else if(ad == 'A4'){
                    size = 210 * 297
                }else if(ad == 'B4'){
                    size = 257 * 364
                }else if(ad == 'B5'){
                    size = 182 * 257
                }else if(ad == '16K'){
                    size = 270 * 195
                }else if(ad == '8K'){
                    size = 270 * 390
                }
                Vue.set(item, 'paperWeight', g); //克重
                Vue.set(item, 'paperPakg', p); //包数
                Vue.set(item, 'paperCopySize', size); //尺寸
                // 吨价
                Vue.set(item, 'tonPrice', price);
                // 箱价
                var boxPrice = vm.calculateBoxPrice(item);
                Vue.set(item, 'boxPrice', boxPrice);
            }
        },
        /* 计算吨价 */
        calculateTonPrice: function (item) {
            var g = item.paperWeight; // 克重
            if (item.goodsType == 'paper'){ //大纸
                var lo = item.paperLen; // 长
                var w = item.paperWidth; // 宽
                // 吨价 = 令价 * 1000 * 1000 * 1000 * 2 / （克重 * 长 * 宽）
                var tonPrice = item.reamPrice * ( 1000 * 1000 * 1000 * 2 ) / ( g * w * lo ) + "";
                return tonPrice.substring(0, (tonPrice.indexOf('.') + 4));
            }else if (data.goodsType == 'copy'){ //复印纸
                // 吨价 = 箱价 * 1000 * 1000 * 1000 * 2 / (克重 * 包数 * 尺寸)
                var tonPrice = item.boxPrice * 1000 * 1000 * 1000 * 2 / (item.paperWeight * item.paperPakg * item.paperCopySize) + "";
                return tonPrice.substring(0, (tonPrice.indexOf('.') + 4));
            }
            return null;
        },
        /* 计算令价 */
        calculateReamPrice: function (item) {
            // 令价 =  吨价 * 克重 * 宽 * 长 / (1000*1000*1000*2)
            var reamPrice = item.tonPrice * item.paperWeight * item.paperWidth * item.paperLen / (1000 * 1000 * 1000 * 2) + "";
            return reamPrice.substring(0, (reamPrice.indexOf('.') + 4));
        },
        /* 计算箱价 */
        calculateBoxPrice: function (item) {
            // 箱价 = 吨价 * 克重 * 包数 * 尺寸 / (1000*1000*1000*2)
            var boxPrice = item.tonPrice * item.paperWeight * item.paperPakg * item.paperCopySize / (1000 * 1000 * 1000 * 2) + "";
            return boxPrice.substring(0, (boxPrice.indexOf('.') + 4));
        },
        /* 商品修改（吨价变动） */
        tonPriceChange: function () {
            var item = vm.update.orderItem;
            if (item.goodsType == 'paper'){
                if (item.paperUnit == 'ton'){
                    item.price = item.tonPrice;
                    item.amount = Math.floor(item.tonPrice * item.nums * 100) / 100;
                }else if (item.paperUnit == 'ream'){
                    var reamPrice = vm.calculateReamPrice(item);
                    item.reamPrice = reamPrice;
                    item.price = item.reamPrice;
                    item.amount = Math.floor(item.reamPrice * item.nums * 100) / 100;
                }
            }else if (item.goodsType == 'copy'){
                var boxPrice = vm.calculateBoxPrice(item);
                item.boxPrice = boxPrice;
                item.price = item.tonPrice;
                item.amount = Math.floor(item.tonPrice * item.nums * 100) / 100;
            }
        },
        /* 商品修改（令价变动） */
        reamPriceChange: function () {
            var item = vm.update.orderItem;
            var tonPrice = vm.calculateTonPrice(item);
            item.tonPrice = tonPrice;
            item.price = item.reamPrice;
            item.amount = Math.floor(item.reamPrice * item.nums * 100) / 100;
        },
        /* 商品修改（箱价变动） */
        boxPriceChange: function () {
            var item = vm.update.orderItem;
            var tonPrice = vm.calculateTonPrice(item);
            item.tonPrice = tonPrice;
            item.price = item.tonPrice;
            item.amount = Math.floor(item.tonPrice * item.nums * 100) / 100;
        },
        /* 商品修改（购买数量变动） */
        itemNumsChange: function () {
            vm.update.orderItem.amount = Math.floor(vm.update.orderItem.price * vm.update.orderItem.nums * 100) / 100;
        },
        /* 审核金额修改 */
        orderPriceChange: function () {
            var discount = Number(vm.audit.discount);
            var costFreight = Number(vm.audit.costFreight);
            vm.audit.payableAmount = Number(vm.update.paperOrderInfo.payableAmount) + discount + costFreight;
        },
        openShipForm: function () {
            // 复制属性值
            var regionPath;
            var sendType;
            if (vm.erpOrder == null){
                vm.shipForm = Object.assign({}, vm.paperOrderInfo);
                // 配送方式
                sendType = vm.paperOrderInfo.pickUp == true ? '1' : '0';
                regionPath = vm.paperOrderInfo.regionPath;
            }else{
                vm.shipForm = Object.assign({}, vm.erpOrder);
                // 配送方式
                sendType = vm.erpOrder.sendType == true ? '1' : '0';
                regionPath = vm.erpOrder.regionPath;
            }
            Vue.set(vm.shipForm, 'sendType', sendType);
            // 回显省市区
            if (!isBlank(regionPath)){
                // 字符型数组
                var regionPathStringArr = regionPath.substring(1, regionPath.length-1).split(",");
                // 整形数组
                var regionPathIntArr = regionPathStringArr.map(function(data){
                    return + data;
                });
                Vue.set(vm.shipForm, 'areaCascader', regionPathIntArr);
            }
            vm.shipFormVisible = true;
        },
        // 修改收货人信息
        changeShipInfo: function () {
            if (vm.erpOrder == null){
                vm.erpOrder = new Object();
                vm.erpOrder.orderNo = vm.paperOrderInfo.orderId;
            }
            vm.erpOrder.shipName = vm.shipForm.shipName;
            vm.erpOrder.shipMobile = vm.shipForm.shipMobile;
            vm.erpOrder.shipAddr = vm.shipForm.shipAddr;
            vm.erpOrder.shipZip = vm.shipForm.shipZip;
            vm.erpOrder.sendType = vm.shipForm.sendType;
            vm.erpOrder.costFreight = vm.shipForm.costFreight;
            vm.erpOrder.shipAreaId = vm.shipForm.shipAreaId;
            vm.erpOrder.shipArea = vm.shipForm.shipArea;

            $.ajax({
                type: "POST",
                url: baseURL + "order/erporder/orderReceiverUpdate",
                contentType: "application/json",
                data: JSON.stringify(vm.erpOrder),
                success: function(r){
                    vm.shipFormVisible = false;
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.getInfo(vm.paperOrderInfo.orderId);
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        
        // 显示发票信息
        openInvoiceFrom:function(){
         	 // 复制属性值
              vm.invoiceFrom = Object.assign({}, vm.paperOrderInfo); 
              vm.invoiceFormVisible = true; //加载数据开启窗口
         },
        // 修改发票信息
         changeTaxInfo(invoiceFrom){
            var  postData = {
            		orderId: vm.paperOrderInfo.orderId,
            		userId: vm.paperOrderInfo.userId,
            		taxType: vm.invoiceFrom.taxType,
            		taxIdentification:vm.invoiceFrom.taxIdentification,
            		taxContent:vm.invoiceFrom.taxContent,
            		taxCompany:vm.invoiceFrom.taxCompany,
            		taxAddr:vm.invoiceFrom.taxAddr,
            		taxTel:vm.invoiceFrom.taxTel,
            		taxAccountName:vm.invoiceFrom.taxAccountName,
            		taxNumber:vm.invoiceFrom.taxNumber,
            	}
            //表单验证
            this.$refs[invoiceFrom].validate((valid) => {
                if (valid) {
                    var url;
                    if(isBlank(vm.paperOrderInfo.taxType)){
                        url = "order/ordertax/save";
                    } else{
                        url = "order/ordertax/update";
                    }
                     $.ajax({
                            type: "POST",
                            url: baseURL + url,
                            contentType: "application/json",
                            data: JSON.stringify(postData),
                            success: function(r){
                                if(r.code === 0){
                                    vm.invoiceFormVisible=false;  //关闭弹出窗口
                                    alert('操作成功', function(index){
                                        vm.getInfo(vm.paperOrderInfo.orderId);
                                    });
                                }else{
                                    alert(r.msg);
                                }
                            }
                     });
                    } else {
                        console.log('error primary!!');
                        return false;
                      }
                });
           },
        // 订单作废
        delPaperOrder: function () {
            vm.pub.orderId = vm.paperOrderInfo.orderId;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单作废",
                area: ['550px', '280px'],
                shadeClose: false,
                scrollbar: false,
                content: jQuery("#remarksLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    var remark = vm.pub.remark;
                    if (isBlank(remark)){
                        alert("请输入作废备注！");
                        return false;
                    }
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderInvalid",
                        contentType: "application/json",
                        data: {
                            'orderId': vm.paperOrderInfo.orderId,
                            'remarks': remark
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.reload();
                                    vm.pub.remark = '';
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
        /* 申请售后 */
        applyService: function () {
            // 跳转申请售后页面 todo 此处应该做初步校验
            window.registerDialogVm.loadData({orderId:vm.paperOrderInfo.orderId});
        },
        // 省市区
        handleItemChange: function (val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length - 1];
            vm.shipForm.shipAreaId = areaId;

            var lableVal = getCascaderObj(val, vm.options);
            var area = lableVal.join(',').replace(new RegExp(',', 'g'), ' ');
            vm.shipForm.shipArea = area;
        },
        // 订单商品修改
        orderItemUpdate: function (index) {
            var item = vm.orderItemList[index];
            // 复制属性值
            vm.update.orderItem = Object.assign({}, item);
            if (typeof vm.update.paperOrderInfo.orderId == 'undefined'){
                vm.update.paperOrderInfo = Object.assign({}, vm.paperOrderInfo);
            }
            // 标识第几个商品
            vm.update.orderItem.index = index;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "修改商品信息",
                area: ['600px', '480px'],
                shadeClose: false,
                content: jQuery("#orderItemLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    var updateItem = vm.update.orderItem;
                    var paperOrderInfo = vm.update.paperOrderInfo;
                    var item = vm.orderItemList[updateItem.index];
                    var p1 = (paperOrderInfo.payableAmount * 100 - item.amount * 100) / 100;
                    var p2 = (p1 * 100 + updateItem.amount * 100) / 100;
                    var p3 = Math.floor(p2 * 100) / 100;
                    paperOrderInfo.payableAmount = p3;
                    item.price = updateItem.price;
                    item.nums = updateItem.nums;
                    item.amount = updateItem.amount;
                    vm.update.orderItemList.push(item);
                    layer.close(index);
                }
            });
        },
        // 大纸商品审核
        paperAudit: function () {
            // 复制属性值
            if (typeof vm.update.paperOrderInfo.orderId == 'undefined'){
                vm.update.paperOrderInfo = Object.assign({}, vm.paperOrderInfo);
            }
            vm.audit.costFreight = vm.paperOrderInfo.costFreight;
            vm.audit.discount = vm.paperOrderInfo.discount;
            vm.audit.payableAmount = vm.update.paperOrderInfo.payableAmount;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "大纸审核",
                area: ['600px', '420px'],
                shadeClose: false,
                content: jQuery("#auditLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    var postData = {
                        orderId: vm.paperOrderInfo.orderId,
                        costFreight: vm.audit.costFreight,
                        discount: vm.audit.discount,
                        payableAmount: vm.audit.payableAmount,
                        remark: vm.pub.remark,
                        orderItemList: vm.update.orderItemList
                    };
                    $.ajax({
                        type: "POST",
                        url: baseURL + "order/paperOrder/paperOrderAudit",
                        contentType: "application/json",
                        data: JSON.stringify(postData),
                        success: function(r){
                            if(r.code === 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.reload();
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
            });
        },
        // 订单完成
        orderFinish: function () {
            vm.pub.orderId = vm.paperOrderInfo.orderId;
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单完成",
                area: ['550px', '280px'],
                shadeClose: false,
                content: jQuery("#remarksLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    $.ajax({
                        type: "GET",
                        url: baseURL + "order/orderinfo/orderFinish",
                        contentType: "application/json",
                        data: {
                            'orderId': vm.paperOrderInfo.orderId,
                            'remarks': vm.pub.remark
                        },
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.pub.remark = '';
                                    vm.reload();
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                },
                btn2: function (index) {
                    layer.close(index);
                    vm.pubremark = '';
                }
            });
        },
        // 订单支付
        orderPay: function () {
            // 设置当前时间
            vm.pay.tPayed = vm.dateFormat(new Date());
            layer.open({
                type: 1,
                skin: 'layui-layer-molv',
                title: "订单支付",
                area: ['700px', '650px'],
                shadeClose: false,
                scrollbar: false,
                content: jQuery("#orderPayLayer"),
                btn: ['保存','取消'],
                btn1: function (index) {
                    var postData = {
                        orderId: vm.paperOrderInfo.orderId,
                        account: vm.pay.account,
                        bank: vm.pay.bank,
                        money: vm.pay.money,
                        payName: vm.pay.payName,
                        memo: vm.pay.memo,
                        paymentTime: vm.pay.tPayed,
                        payAppId: vm.pay.payAppId
                    }
                    $.ajax({
                        type: "POST",
                        url: baseURL + "order/orderinfo/orderPayment",
                        contentType: "application/json",
                        data: JSON.stringify(postData),
                        success: function(r){
                            if(r.code == 0){
                                layer.close(index);
                                alert('操作成功', function(index){
                                    vm.pay.bank = '';
                                    vm.pay.money = '';
                                    vm.pay.payAppId = '';
                                    vm.pay.payName = '';
                                    vm.pay.memo = '';
                                    vm.pay.tPayed = '';
                                    vm.getInfo(vm.paperOrderInfo.orderId);
                                });
                            }else{
                                alert(r.msg);
                            }
                        }
                    });
                }
            });
        },
        /* 发货 */
        send: function(orderId){
            var that = this
            $.ajax({
                type: "GET",
                url: baseURL + "order/paperOrder/sendLogisticsInfo?orderId=" + orderId,
                contentType: "application/json",
                data: null,
                success: function(r){
                    if(r.code == 0){
                        vm.erpOrder = r.erpOrder;
                        vm.orderItemList = r.orderItemEntityList;
                        vm.logisticsTypeList = r.logisticsTypeList;
                        that.$refs.multipleTable.toggleAllSelection();
                        vm.erpLogisticsEntity = {
                            toPeople: vm.erpOrder.shipName,
                            toPhone:  vm.erpOrder.shipMobile+""+(vm.erpOrder.shipTel==null?"":","+vm.erpOrder.shipTel),
                            toAddress: vm.erpOrder.shipAddr,
                            toArea: vm.erpOrder.shipArea,
                            toAreaId: vm.erpOrder.shipAreaId,
                            sendType: 3,
                            logiType: 2
                        };

                        vm.showList = false;
                        vm.showOrder = false;
                        vm.showLogi = true;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        // 参数验证
        validator: function () {
            if(vm.erpLogisticsEntity.logiType != 3){
                if (isBlank(vm.erpLogisticsEntity.logisticsId)) {
                    alert("物流方式不能为空");
                    return false;
                }
            }
            if (isBlank(vm.erpLogisticsEntity.toPeople)) {
                alert("收货人不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toAreaId)) {
                alert(" 收货地区不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toArea)) {
                alert("收货地址不能为空");
                return false;
            }
            return true;
        },
        // 物流类型改变
        logiTypeChange: function (value) {
            for (var i = 0, logisticsType; logisticsType = vm.logisticsTypeList[i++];) {
                // 紫云物流 不填写配送单号
                if (logisticsType.logisticsId == value){
                    vm.erpLogisticsEntity.logiCompany = logisticsType.logisticsName;
                    if (logisticsType.logisticsName.indexOf("紫云-") == 0){
                        vm.showLogiNo = false;
                    }
                }else {
                    vm.showLogiNo = true;
                }
            }
        },
        // 监听订单明细勾选change事件
        orderItemSelectionChange: function (row) {
            var list = new Array();
            for (var i = 0, orderItem; orderItem = row[i++];) {
                var logisticsItem = {
                    orderItemId: orderItem.itemId,
                    orderItemName: orderItem.name,
                    quantity: orderItem.nums
                }
                list.push(logisticsItem);
            }
            vm.logisticsItemList = list;
        },
        // 添加物流信息保存
        saveLogistics: function () {
            // 验证参数
            if (!vm.validator()) {
                return false;
            }
            var erpLogisticsDto = {
                erpLogisticsEntity: vm.erpLogisticsEntity,
                erpLogisticsItemList: vm.logisticsItemList
            }
            erpLogisticsDto.erpLogisticsEntity.orderNo = vm.erpOrder.orderNo;
            erpLogisticsDto.erpLogisticsEntity.sellerId = vm.erpOrder.thirdMerchantId;
            erpLogisticsDto.erpLogisticsEntity.orderId = vm.erpOrder.orderNo;
            erpLogisticsDto.erpLogisticsEntity.fromPeople = "ziyun";
            erpLogisticsDto.erpLogisticsEntity.fromArea = "湖北 武汉 江汉区";
            erpLogisticsDto.erpLogisticsEntity.fromAddress = "江汉区常青三路17B9-13";
            erpLogisticsDto.erpLogisticsEntity.fromPhone = "400-000-2519";
            $.ajax({
                type: "POST",
                url: baseURL + "order/paperOrder/saveOrderLogisticsInfo",
                contentType: "application/json",
                data: JSON.stringify(erpLogisticsDto),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        /* 物流发送 */
        sendTypeChange: function (value) {
            if (value == 1) {
                vm.showSendDetail = false;
            } else {
                vm.showSendDetail = true;
            }
        },
        reload: function (event) {
            vm.showList = true;
            vm.showOrder = false;
            vm.showLogi = false;
            vm.update.paperOrderInfo = {};
            vm.update.orderItem = {};
            vm.update.orderItemList = [];
            status = 0;
            $("#jqGrid").jqGrid('setGridParam',{
                page: 1,
                postData:{
                    'orderId': vm.q.orderId,
                    'status': vm.q.status,
                    'memberName': vm.q.memberName,
                    'orderType': vm.q.orderType,
                    'beginCreatetime' : vm.q.beginCreatetime,
                    'endCreatetime' : vm.q.endCreatetime,
                    'auditStatus' : vm.q.auditStatus,
                    'payStatus' : vm.q.payStatus,
                },
            }).trigger("reloadGrid");
        },
        reset: function () {
            vm.q.orderId = '';
            vm.q.memberName = '';
            vm.q.status = '';
            vm.q.orderType = '';
            vm.q.beginCreatetime = '';
            vm.q.endCreatetime = '';
            vm.q.auditStatus = '';
            vm.q.payStatus = '';
            vm.reload();
        }
	}
});

/**
 * 省市区级联选择
 * @param val
 * @param opt
 */
function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm in opt) {
            if (opt[itm].value == value) {
                var label = opt[itm].label;
                opt = opt[itm].children; return label;
            }
        }
        return null;
    });
}